<template>
  <div class="tab-list-container">
    <div class="filter-container">
      <el-input
          v-model="searchQuery"
          placeholder="请输入标签名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter="handleSearch"
      />
      <el-button type="primary" class="filter-item" @click="handleSearch">搜索</el-button>
      <el-button type="success" class="filter-item" @click="handleCreate">新增标签</el-button>
    </div>

    <el-table
        v-loading="loading"
        :data="tabList"
        border
        style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80"/>
      <el-table-column prop="createTime" label="创建时间" min-width="150">
        <template #default="{row}">
          <span>
            {{ row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="color" label="颜色" min-width="150">
        <template #default="{row}">
          <div :style="{backgroundColor: row.color, height: '20px', width: '60px'}"></div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{row}">
          <span>
            {{ formatTime(new Date(row.createTime)) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="更新时间" width="180">
        <template #default="{row}">
          <span>
            {{ formatTime(new Date(row.updateTime)) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{row}">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑标签对话框 -->
    <el-dialog
        :title="dialogStatus === 'create' ? '新增标签' : '编辑标签'"
        v-model="dialogVisible"
        width="30%"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入标签名称"/>
        </el-form-item>
        <el-form-item label="标签颜色" prop="color">
          <el-color-picker v-model="form.color"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {findAllTag, saveTag, updateTag, deleteTagById} from '@/api/tag'

export default {
  name: "TabManagement",
  setup() {
    const loading = ref(false)
    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const tabList = ref([])
    const dialogVisible = ref(false)
    const dialogStatus = ref('')
    const formRef = ref(null)

    const form = reactive({
      id: null,
      name: '',
      color: '',
    })

    const rules = {
      name: [
        {required: true, message: '请输入标签名称', trigger: 'blur'},
        {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
      ],
      color: [
        {required: true, message: '请输入标签颜色'}
      ]
    }

    // 获取所有标签
    const getTabs = async () => {
      loading.value = true
      try {
        const response = await findAllTag()
        tabList.value = response.data || []
        total.value = tabList.value.length
      } catch (error) {
        console.error('获取标签列表失败:', error)
        ElMessage.error('获取标签列表失败')
      } finally {
        loading.value = false
      }
    }

    // 搜索标签
    const handleSearch = () => {
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        const filteredTabs = tabList.value.filter(tab =>
            tab.name.toLowerCase().includes(query)
        )
        tabList.value = filteredTabs
        total.value = filteredTabs.length
      } else {
        getTabs()
      }
    }

    // 新增标签
    const handleCreate = () => {
      dialogStatus.value = 'create'
      form.id = undefined
      form.name = ''
      form.color = ''
      dialogVisible.value = true
      // 在下一个事件循环中重置表单验证
      setTimeout(() => {
        if (formRef.value) {
          formRef.value.resetFields()
        }
      })
    }

    // 编辑标签
    const handleEdit = (row) => {
      dialogStatus.value = 'update'
      form.id = row.id
      form.name = row.name
      form.color = row.color
      dialogVisible.value = true
    }

    // 删除标签
    const handleDelete = (row) => {
      ElMessageBox.confirm(
          `确定要删除标签 "${row.name}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(async () => {
        try {
          await deleteTagById(row.id)
          ElMessage.success('删除成功')
          getTabs()
        } catch (error) {
          console.error('删除标签失败:', error)
          ElMessage.error('删除标签失败')
        }
      }).catch(() => {
        // 取消删除操作
      })
    }

    // 提交表单
    const submitForm = () => {
      if (!formRef.value) return

      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (dialogStatus.value === 'create') {
              await saveTag(form)
              ElMessage.success('新增标签成功')
            } else {
              await updateTag(form)
              ElMessage.success('更新标签成功')
            }
            dialogVisible.value = false
            await getTabs()
          } catch (error) {
            console.error('保存标签失败:', error)
            ElMessage.error('保存标签失败')
          }
        }
      })
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      getTabs()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      getTabs()
    }

    // 页面加载时获取标签列表
    onMounted(() => {
      getTabs()
    })


    const formatTime = (date) => {
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hours = date.getHours();
      let minutes = date.getMinutes();
      let seconds = date.getSeconds();

      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      hours = hours < 10 ? "0" + hours : hours;
      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    return {
      loading,
      searchQuery,
      tabList,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      dialogStatus,
      form,
      rules,
      formRef,
      handleSearch,
      handleCreate,
      handleEdit,
      handleDelete,
      submitForm,
      handleSizeChange,
      handleCurrentChange,
      formatTime
    }
  }
}
</script>

<style scoped>
.tab-list-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
